package br.com.agenda.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.incrementer.HsqlSequenceMaxValueIncrementer;
import org.springframework.stereotype.Repository;

import br.com.agenda.dao.ClienteDAO;
import br.com.agenda.entity.Cliente;

@Repository
public class ClienteDaoImpl extends JdbcDaoSupport implements ClienteDAO {

	private HsqlSequenceMaxValueIncrementer sequence;

	@Autowired
	public void setDataSourcex(DataSource dataSource) {

		super.setDataSource(dataSource);

		sequence = new HsqlSequenceMaxValueIncrementer(dataSource, "seq");
	}

	public Cliente loadById(Cliente cliente) {

		
		return null;
		
	}

	public List<Cliente> findAll() {

		String sql = "SELECT ID, FIRSTNAME, LASTNAME, STREET, CITY FROM CUSTOMER";

		List<Cliente> clientes = new ArrayList<Cliente>();

		List<Map<String, Object>> rows = getJdbcTemplate().queryForList(sql);

		for (Map<String, Object> row : rows) {
			Cliente cliente = new Cliente();
			cliente.setId((Integer) (row.get("ID")));
			cliente.setNome((String) (row.get("FIRSTNAME")));
			cliente.setUltimoNome((String) (row.get("LASTNAME")));
			cliente.setRua((String) (row.get("STREET")));
			cliente.setCidade((String) (row.get("CITY")));
			clientes.add(cliente);
		}

		return clientes;
	}

	public void save(Cliente cliente) {

		Integer seqValue = sequence.nextIntValue();

		String sql = "INSERT INTO CUSTOMER (ID, FIRSTNAME, LASTNAME, STREET, CITY ) VALUES (?, ?, ?, ?, ?)";

		getJdbcTemplate().update(sql, seqValue, cliente.getNome(),
				cliente.getUltimoNome(), cliente.getRua(), cliente.getCidade());

		cliente.setId(seqValue);

	}

	public void remove(Cliente cliente) {

		getJdbcTemplate().update("DELETE FROM CUSTOMER WHERE ID=?",
				cliente.getId());

	}
}
